package models;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

import javax.persistence.*;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sun.mail.imap.protocol.UID;

import controllers.Secure;
import controllers.Users;

import play.data.validation.*;
import play.db.jpa.*;
import play.libs.WS;

@Entity
public class SocialProfile extends Model
{
	@Required
	@Column(unique = true)
	public String			access_token;

	@URL
	public String			link;

	public String			gender;

	public long				uid;

	public String			username;

	public String			displayName;

	@URL
	public String			ppLink;

	public String			updated_time;

	// bi-directional one-to-many, owning side
	@ManyToOne
	public AbstractProfile	abstractProfile;

	public SocialProfile(String access_token, AbstractProfile abstractProfile)
	{
		super();
		this.access_token = access_token;
		this.link = "";
		this.gender = "";
		this.uid = 0;
		this.username = "";
		this.displayName = "";
		this.ppLink = "";
		this.updated_time = "";
		this.abstractProfile = abstractProfile;
	}

	public static List<String> manageStatus(
			@Required AbstractProfile abstractProfile)
	{
		System.out.println("Running in SocialProfile.manageStatus method");
		List<String> statusMsg = new LinkedList<String>();
		for (int j = 0; j < abstractProfile.profileList.size(); j++)
		{
			String tempURL = "https://graph.facebook.com/"
					+ abstractProfile.profileList.get(j).uid
					+ "/statuses?access_token="
					+ WS.encode(abstractProfile.profileList.get(j).access_token)
					+ "&limit=1";

			JsonObject me = WS.url(tempURL).get().getJson().getAsJsonObject();
			JsonArray jsArr = me.getAsJsonArray("data");
			String status = "";
			for (JsonElement jsEl : jsArr)
			{
				status = jsEl.getAsJsonObject().getAsJsonPrimitive("message")
						.getAsString();
				System.out.println("Current status: " + status);
			}

			statusMsg.add(status);

		}
		return statusMsg;
	}

	public static SocialProfile findByUID(long uID)
	{
		List<SocialProfile> allSocialProfiles = SocialProfile.findAll();
		for (int i = 0; i < allSocialProfiles.size(); i++)
		{
			SocialProfile temp = allSocialProfiles.get(i);
			if (temp.uid == uID)
			{
				return temp;
			}
		}
		return null;

	}
}
